import React from 'react';
import useWebSocket from './useWebSocket.js';
import { ConnectionStatus } from './types.js';

/**
 * WebSocket连接状态显示组件
 * 提供美观的连接状态指示器和连接控制功能
 */
const WebSocketStatus = ({ 
  showDetails = true, 
  showControls = true,
  position = 'top-right',
  className = '' 
}) => {
  const {
    status,
    reconnectAttempts,
    error,
    isConnected,
    isConnecting,
    isReconnecting,
    isDisconnected,
    hasError,
    connect,
    disconnect,
    clearError
  } = useWebSocket({
    autoConnect: false // 手动控制连接
  });

  // 获取状态显示信息
  const getStatusInfo = () => {
    switch (status) {
      case ConnectionStatus.CONNECTED:
        return {
          text: '已连接',
          color: 'bg-green-500',
          icon: '✓',
          description: 'WebSocket连接正常'
        };
      case ConnectionStatus.CONNECTING:
        return {
          text: '连接中',
          color: 'bg-yellow-500',
          icon: '⟳',
          description: '正在建立WebSocket连接...'
        };
      case ConnectionStatus.RECONNECTING:
        return {
          text: `重连中 (${reconnectAttempts})`,
          color: 'bg-orange-500',
          icon: '↻',
          description: `正在尝试第 ${reconnectAttempts} 次重连...`
        };
      case ConnectionStatus.DISCONNECTED:
        return {
          text: '未连接',
          color: 'bg-gray-500',
          icon: '✗',
          description: 'WebSocket连接已断开'
        };
      case ConnectionStatus.ERROR:
        return {
          text: '连接错误',
          color: 'bg-red-500',
          icon: '⚠',
          description: error || 'WebSocket连接发生错误'
        };
      default:
        return {
          text: '未知状态',
          color: 'bg-gray-500',
          icon: '?',
          description: '未知的连接状态'
        };
    }
  };

  const statusInfo = getStatusInfo();

  // 处理连接/断开连接
  const handleConnect = async () => {
    const token = localStorage.getItem('auth_token');
    if (token) {
      await connect(token);
    } else {
      console.error('未找到认证token，请先登录');
    }
  };

  const handleDisconnect = () => {
    disconnect();
  };

  // 位置样式
  const getPositionClass = () => {
    switch (position) {
      case 'top-left':
        return 'top-4 left-4';
      case 'top-right':
        return 'top-4 right-4';
      case 'bottom-left':
        return 'bottom-4 left-4';
      case 'bottom-right':
        return 'bottom-4 right-4';
      default:
        return 'top-4 right-4';
    }
  };

  return (
    <div 
      className={`
        fixed z-50 ${getPositionClass()} 
        bg-white dark:bg-gray-800 
        shadow-lg rounded-lg border 
        border-gray-200 dark:border-gray-700
        p-3 min-w-[200px] max-w-[300px]
        transition-all duration-300
        ${className}
      `}
    >
      {/* 状态指示器 */}
      <div className="flex items-center justify-between mb-2">
        <div className="flex items-center space-x-2">
          <div 
            className={`
              w-3 h-3 rounded-full animate-pulse
              ${statusInfo.color}
            `}
            title={statusInfo.description}
          />
          <span className="text-sm font-medium text-gray-900 dark:text-white">
            {statusInfo.icon} {statusInfo.text}
          </span>
        </div>
        
        {showControls && (
          <div className="flex space-x-1">
            {!isConnected && !isConnecting && (
              <button
                onClick={handleConnect}
                className="px-2 py-1 text-xs bg-blue-500 text-white rounded hover:bg-blue-600 transition-colors"
                title="连接WebSocket"
              >
                连接
              </button>
            )}
            {isConnected && (
              <button
                onClick={handleDisconnect}
                className="px-2 py-1 text-xs bg-red-500 text-white rounded hover:bg-red-600 transition-colors"
                title="断开WebSocket连接"
              >
                断开
              </button>
            )}
          </div>
        )}
      </div>

      {/* 详细信息 */}
      {showDetails && (
        <div className="text-xs text-gray-600 dark:text-gray-400 space-y-1">
          <div>{statusInfo.description}</div>
          
          {isReconnecting && reconnectAttempts > 0 && (
            <div>重连尝试: {reconnectAttempts} 次</div>
          )}
          
          {hasError && error && (
            <div className="flex items-center justify-between">
              <span className="text-red-500">{error}</span>
              <button
                onClick={clearError}
                className="text-red-400 hover:text-red-600 transition-colors"
                title="清除错误"
              >
                ×
              </button>
            </div>
          )}
        </div>
      )}

      {/* 连接质量指示器（仅当连接时显示） */}
      {isConnected && (
        <div className="mt-2">
          <div className="flex items-center justify-between text-xs">
            <span className="text-gray-500">连接质量</span>
            <div className="flex space-x-1">
              {[1, 2, 3].map((bar) => (
                <div
                  key={bar}
                  className={`
                    w-1 h-3 rounded-full transition-all duration-500
                    ${bar <= 2 ? 'bg-green-400' : 'bg-gray-300'}
                    ${bar === 3 && 'animate-pulse'}
                  `}
                />
              ))}
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default WebSocketStatus;

// 简化的状态指示器组件（仅显示状态点）
export const WebSocketStatusDot = ({ size = 'medium' }) => {
  const { status } = useWebSocket({ autoConnect: false });
  
  const getDotSize = () => {
    switch (size) {
      case 'small': return 'w-2 h-2';
      case 'medium': return 'w-3 h-3';
      case 'large': return 'w-4 h-4';
      default: return 'w-3 h-3';
    }
  };

  const getStatusColor = () => {
    switch (status) {
      case ConnectionStatus.CONNECTED: return 'bg-green-500';
      case ConnectionStatus.CONNECTING: return 'bg-yellow-500 animate-pulse';
      case ConnectionStatus.RECONNECTING: return 'bg-orange-500 animate-pulse';
      case ConnectionStatus.DISCONNECTED: return 'bg-gray-400';
      case ConnectionStatus.ERROR: return 'bg-red-500 animate-pulse';
      default: return 'bg-gray-400';
    }
  };

  return (
    <div 
      className={`
        ${getDotSize()} rounded-full inline-block
        ${getStatusColor()}
      `}
      title={`WebSocket状态: ${status}`}
    />
  );
};
